<?php

class Http{
    CONST HOST = "0.0.0.0";
    CONST PORT = 8811;

    public $http = null;
    public function __construct() {
        $this->http = new swoole_http_server(self::HOST, self::PORT);

        $this->http->set(
            [
                'worker_num' => 4,
                'task_worker_num' => 4,
                'enable_static_handler' => true,
                'document_root' => "/home/work/study/swoole_mooc/thinkphp/public/static",

            ]
        );
        $this->http->on("workerstart", [$this, 'onWorkerStart']);
        $this->http->on("request", [$this, 'onRequest']);
        $this->http->on("task", [$this, 'onTask']);
        $this->http->on("finish", [$this, 'onFinish']);
        $this->http->on("close", [$this, 'onClose']);

        $this->http->start();
    }

    /**
     * 监听ws连接事件
     * @param $ws
     * @param $request
     */
    public function onWorkerStart( $server,$worker_id) {
        define('APP_PATH', __DIR__ . '/../application/');
        require __DIR__ . '/../thinkphp/base.php';
//        require __DIR__ . '/../thinkphp/start.php';
    }

    public function onRequest( $request,$response) {
        $_SERVER=[];
        $_GET=[];
        $_POST=[];
        if(isset($request->server)){
            foreach ($request->server as $k=>$v){
                $_SERVER[strtoupper($k)] = $v;
            }
        }
        if(isset($request->header)){
            foreach ($request->header as $k=>$v){
                $_SERVER[strtoupper($k)] = $v;
            }
        }
        if(isset($request->get)){
            foreach ($request->get as $k=>$v){
                $_GET[$k] = $v;
            }
        }
        if(isset($request->post)){
            foreach ($request->post as $k=>$v){
                $_POST[$k] = $v;
            }
        }
        ob_start();
        // 2. 执行应用
        $_POST['http_server']=$this->http;
        try{
            think\App::run()->send();
        }catch (\Exception $e){

        }

        $res =ob_get_contents();
        ob_end_clean();
        $response->end($res);
    }

    public function onTask($serv, $taskId, $workerId, $data) {
        //分发task任务机制，让不同的任务走不同的逻辑

        $obj=new app\common\lib\task\Task();

        $method = $data['method'];
        $flag =$obj->$method($data['data']);
        return $flag; // 告诉worker
    }

    /**
     * @param $serv
     * @param $taskId
     * @param $data
     */
    public function onFinish($serv, $taskId, $data) {
        echo "taskId:{$taskId}\n";
        echo "finish-data-sucess:{$data}\n";
    }

    /**
     * close
     * @param $ws
     * @param $fd
     */
    public function onClose($ws, $fd) {
        echo "clientid:{$fd}\n";
    }

}
new Http();